package cadtoolbox.utils;

import cadtoolbox.graphical.AnimatedSequences;

import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;

import org.apache.commons.math3.ode.FirstOrderIntegrator;

import cadtoolbox.model.Constants;
import cadtoolbox.model.OligoGraph;
import cadtoolbox.model.OligoSystem;
import cadtoolbox.model.SequenceVertex;

public class MyWorker extends SwingWorker implements PluggableWorker {

	private FirstOrderIntegrator integ;
	private OligoSystem syst;
	private ProgressMonitor cop;
	protected OligoGraph graph;
	
	public MyWorker(OligoSystem syst, OligoGraph graph){
		this.graph = graph;
		this.syst = syst;
	}
	
	@Override
	protected Object doInBackground() throws Exception {
		setProgress(0);
		JFrame plotPanel = new JFrame();
		double[][] results = syst.calculateTimeSeries(this);
		//System.out.println("Finished simulating");
		double[][] savedActivity = syst.getActivity();
		
		if(this.graph.autoplot == null || !cadtoolbox.utils.PlotExpData.autoplot){
			PlotExpData plot = new PlotExpData("Plot", results, savedActivity, 0.0, 1.0, syst.giveNames(), null, "Time (min)", "Concentration (nM)", (OligoGraph<SequenceVertex,String>)this.graph);

			this.graph.autoplot = plot;
			plotPanel.add(plot);
			plotPanel.pack();
			plotPanel.addWindowListener(new java.awt.event.WindowListener(){

			@Override
			public void windowActivated(WindowEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowClosed(WindowEvent arg0) {
				
			}

			@Override
			public void windowClosing(WindowEvent arg0) {
				graph.autoplot = null;
				
			}

			@Override
			public void windowDeactivated(WindowEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowDeiconified(WindowEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowIconified(WindowEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowOpened(WindowEvent arg0) {
				// TODO Auto-generated method stub
				
			}
			
		});
		plotPanel.setVisible(true);
		} else {
			this.graph.autoplot.updatePlot(results,savedActivity, 0.0, 0.1, syst.giveNames());
		}
		
		return null;
	}
	
	@Override
	protected void done(){
		cop.close();
	}
	
	public void setCustomProgress(int time){
		//System.out.println(time);
		
		this.firePropertyChange("progress", time-1, time);
		//setProgress(time);
		//cop.setProgress(time);
	}

	public void setProg(ProgressMonitor cop){
		this.cop = cop;
	}

	@Override
	public void cancel() {
		super.cancel(true);
	}

}
